
(function ($, win, doc) {
    // 创建下拉列表构造函数
    function Select(ele, opt) {
        this.$element = ele;
        this.defaults = {
            isChecked: false,//是否可以多选
            isSearch: false,//是否可以搜索
            isDelete: false,//是否可以删除
            place: 'bottom',//位置 默认bottom，可选top
            height: '160',//选择框高度 默认160px
            placeholder: '',//默认title提示
            selected: [],//默认选中值
            getClickSelect: function (list) {
            },//每次点击下拉框的回调
            data: [],//下拉数据
            disabled: false,//是否可点击
            dataField: {//下拉数据字段
                text: 'name',
                id: 'id'
            }
        }
        this.options = $.extend({}, this.defaults, opt);
    };
    Select.prototype = {
        constructor: Select,
        bindEvent: function () {
            var that = this,
                defaults = this.options,
                $element = this.$element;
            if (defaults.disabled) {
                $element.find('.wui-select-title').css('cursor', 'no-drop');
            } else {
                $element.find('.wui-select-title').css('cursor', 'pointer');
            }
            $element.find('.wui-select-title').off('click').on('click', function () {
                if (defaults.disabled) {
                    return false;
                } else {
                    $element.find('.wui-select-title').css('cursor', 'pointer');
                    $element.find('.wui-select-content').stop().slideToggle();
                }
            });
            $('html').click(function (e) {
                var tag = false;
                $('.wui-select').each(function (index, item) {
                    tag = $.contains(item, e.target);
                    if (!tag) {
                        $(item).find('.wui-select-content').stop().slideUp();
                    }
                })
            })
            var stopBubble = function () {//阻止冒泡
                $element.find('.wui-select-content').on('click', function (e) {
                    window.event ? window.event.cancelBubble = true : e.stopPropagation();
                })
            };
            var placeholder = function () {//placeholder
                if (!$element.find('.wui-select-title').html()) {
                    $element.find('.wui-select-title').html('<p>' + defaults.placeholder + '</p>')
                } else {
                    $element.find('.wui-select-title>p').remove();
                }
            }
            placeholder();//初始化先调用一下
            var selectChecked = function (that) {//多选title和下拉数据对应
                if ($(that).hasClass('active')) {//选中并且title上面不存在
                    $element.find('.wui-select-title').append('<span _id=' + $(that).attr("_id") + '>' + $(that).find('div').text() + '</span>');
                } else {
                    var that_id = $(that).attr('_id');
                    var titleSpan = $element.find('.wui-select-title span');
                    for (var i = 0; i < titleSpan.length; i++) {
                        if (titleSpan.eq(i).attr('_id') == that_id) {
                            titleSpan.eq(i).remove();
                        }
                    }
                }
            };
            if (defaults.isChecked) {//多选
                stopBubble();
                $element.find('.wui-select-item li').off('click').on('click', function (e) {
                    var e = e || window.event;
                    $(this).toggleClass('active');
                    selectChecked(this);
                    if (typeof defaults.getClickSelect == 'function' && e.originalEvent) {//回调
                        defaults.selected = that.getSelectValue();
                        defaults.getClickSelect(defaults.selected, that.getSelectObj(), that);
                    }
                    placeholder(defaults.selected);
                });
            } else {//单选
                $element.find('.wui-select-item li').off('click').on('click', function (e) {
                    var e = e || window.event;
                    $(this).toggleClass('active').siblings().removeClass('active');
                    if ($(this).hasClass('active')) {
                        $element.find('.wui-select-title').html('<span _id=' + $(this).attr("_id") + '>' + $(this).find('div').text() + '</span>')
                    } else {
                        $element.find('.wui-select-title').html('');
                    }
                    $element.find('.wui-select-content').slideUp();
                    if (typeof defaults.getClickSelect == 'function' && e.originalEvent) {//回调
                        defaults.selected = that.getSelectValue();
                        defaults.getClickSelect(defaults.selected, that.getSelectObj(), that);
                    }
                    placeholder(defaults.selected);
                });
            }

            that.setDefault(defaults.selected);//设置selected
            if (defaults.isSearch) {//搜索
                var timer,
                    flag = true;
                $element.find('.wui-select-search').off('input propertychange').on('input propertychange', function () {
                    searchEle = $element.find('.wui-select-search'),
                        itemLi = $element.find('.wui-select-item li');
                    if (flag) {
                        flag = false;
                        timer = setTimeout(function () {
                            var searchVal = searchEle.val();
                            $.each(itemLi, function (index, item) {
                                var itemVal = $(item).find('div').text();
                                if (itemVal.indexOf(searchVal) !== -1) {
                                    $(item).show();
                                } else {
                                    $(item).hide();
                                }
                            })
                            flag = true;
                        }, timer ? 200 : 0)
                    }
                })
            }

            $element.find('.wui-select-item').css('max-height', defaults.height + 'px');//高度

            if (defaults.place == "top") {//显示位置
                $element.find('.wui-select-content').addClass('wui-select-top');
            } else {
                $element.find('.wui-select-content').addClass('wui-select-bottom');
            }
            return this;
        },
        getSelectEach: function (type) { //type 0--获取选中id 1--获取选中text 2--获取选中obj
            var that = this;
            var titleSpan = this.$element.find('.wui-select-title span'),
                arr = [],
                obj;
            for (var i = 0; i < titleSpan.length; i++) {
                if (type == 0) {
                    arr.push(titleSpan.eq(i).attr('_id'));
                } else if (type == 1) {
                    arr.push(titleSpan.eq(i).text());
                }
            }
            if (type == 2) {
                var data = that.options.data;
                var id = that.options.dataField.id;
                $.each(data, function (index, item) {
                    $.each(that.options.selected, function (index2, item2) {
                        if (item[id] == item2) {
                            arr.push(item)
                        }
                    })
                })
            }
            return arr;
        },
        getSelectValue: function () {
            return this.getSelectEach(0);
        },
        getSelectText: function () {
            return this.getSelectEach(1);
        },
        getSelectObj: function () {
            return this.getSelectEach(2);
        },
        setDefault: function (titleDefault, type) {//设置title显示的值
            if (titleDefault.length == 0) {
                this.options.selected = [];
                this.$element.find('.wui-select-item li').removeClass('active');
                this.$element.find('.wui-select-title').html('<p>' + this.options.placeholder + '</p>')
            } else {
                this.options.selected = titleDefault;
            }
            if (this.options.isChecked) {//多选--默认值
                var items = this.$element.find('.wui-select-item li'),
                    dfs;
                for (var i = 0; i < items.length; i++) {
                    item_id = $(items[i]).attr('_id');
                    for (var j = 0; j < titleDefault.length; j++) {
                        if (item_id == titleDefault[j]) {
                            $(items[i]).click();
                        }
                    }

                }
            } else {//单选--默认值
                if (titleDefault.length <= 1) {//有默认值 单选--只能有一个默认值
                    var dfs = titleDefault[0];
                    this.$element.find('.wui-select-item li[_id=' + dfs + ']').click();
                } else {
                    throw "单选只能有一个默认值";
                    return;
                }
            }
        },
        setDisabled: function (tag) {
            if (typeof tag == 'boolean') {
                this.options.disabled = tag;
                if (this.options.disabled) {
                    this.$element.find('.wui-select-title').css('cursor', 'no-drop');
                } else {
                    this.$element.find('.wui-select-title').css('cursor', 'pointer');
                }
            } else {
                throw "setDisabled方法传参类型错误"
                return;
            }
        },
        errorType: function () {//检验传参是否有误
            if (typeof this.options.isChecked !== "boolean") {
                throw "isChecked参数类型错误"
                return;
            }
            if (typeof this.options.isSearch !== "boolean") {
                throw "isSearch参数类型错误"
                return;
            }
            if (typeof this.options.isDelete !== "boolean") {
                throw "isDelete参数类型错误"
                return;
            }
            if (!this.options.data instanceof Array) {
                throw "data参数类型错误"
                return;
            }
            // if (this.options.dataField.text.length == 0 || this.options.dataField.id.length == 0) {
            //     throw "dataField参数text和id为必填项"
            //     return;
            // }
        },
        init: function () {
            this.errorType();//检验传参是否有误
            var options = this.options,
                isChecked = options.isChecked,
                isSearch = options.isSearch,
                isDelete = options.isDelete,
                defaultShow = options.defaultShow,
                data = options.data,
                dataField = options.dataField,
                _text = dataField.text,
                _id = dataField.id,
                htmlStr = '<div class="wui-select"><div class="wui-select-title"></div><div class="wui-select-content">';

            if (isSearch) {//是否有搜索
                htmlStr += '<input type="text" name="wui-select-search" placeholder="搜索" class="wui-select-search">'
            }
            ;
            if (data.length && _text && _id) {//遍历数据
                htmlStr += '<ul class="wui-select-item">';
                for (var i = 0; i < data.length; i++) {
                    htmlStr += '<li _id="' + data[i][_id] + '"><div>' + data[i][_text] + '</div><span>✔</span></li>';
                    if (data[i].selected) {
                        this.options.selected.push(data[i][_id])
                    }
                }
                htmlStr += '</ul>';
            }

            htmlStr += '</div></div>';

            this.$element.html(htmlStr);

            return this.bindEvent();
        }
    }
    $.fn.SelectPlugin = function (options) {
        var select = new Select(this, options);
        return select.init();
    }
})(jQuery, window, document)

